import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import SearchPopup from '../views/SearchPopup.vue'
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { activenum: 0 },
    children: [
      {
        path: '/home/searchpopup',
        name: 'SearchPopup',
        component: SearchPopup
      }
    ]
  },
  {
    path: '/topic',
    name: 'Topic',
    meta: { activenum: 1, isShowTab: true },
    component: () => import('../views/Topic.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    meta: { activenum: 2, isShowTab: true },
    component: () => import('../views/Cart.vue')
  },
  {
    path: '/category',
    name: 'Category',
    meta: { activenum: 3, isShowTab: true },
    component: () => import('../views/Category.vue')
  },
  {
    path: '/user',
    name: 'User',
    meta: { activenum: 4, isShowTab: true },
    component: () => import('../views/User.vue')
  },
  {
    path: '/productdetail',
    name: 'ProductDetail',
    component: () => import('../views/ProductDetail.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.name === 'Cart') {
    if (token) {
      next()
    } else {
      setTimeout(() => next('/user'), 1000)
    }
  }

  next()
})

export default router
